import os
import sys
import logging
from logging.handlers import TimedRotatingFileHandler
from config.config import config


class LogLevel:
    CRITICAL = logging.CRITICAL
    FATAL = logging.FATAL
    ERROR = logging.ERROR
    WARNING = logging.WARNING
    WARN = logging.WARN
    INFO = logging.INFO
    DEBUG = logging.DEBUG
    NOTSET = logging.NOTSET


__loglevel = {
    "critical": logging.CRITICAL,
    "fatal": logging.FATAL,
    "error": logging.ERROR,
    "warning": logging.WARNING,
    "warn": logging.WARN,
    "info": logging.INFO,
    "debug": logging.DEBUG,
    "notset": logging.NOTSET
}

__default_log_path = os.path.join(config.home_path, config.get("logger", "log_path"))
__default_log_name = config.get("logger", "log_name")
__default_log_level = __loglevel.get(config.get("logger", "level"), LogLevel.INFO)


def _logger_define_multi_file(log_path, log_name, log_level=logging.INFO):
    # 判断响应的文件是否存在
    if not os.path.exists(log_path):
        os.makedirs(log_path)
    info_dir = os.path.join(log_path, "info_{}.log".format(log_name))
    error_dir = os.path.join(log_path, "error_{}.log".format(log_name))

    # 返回一个logger对象，如果没有指定名字将返回root logger
    log = logging.getLogger()

    # 定义日志输出格式
    format = config.get("logger", "format")
    fmt = logging.Formatter(format)

    # 设置日志控制台输出
    # stream_handler = logging.StreamHandler(sys.stdout)
    stream_handler = log.handlers[0] if len(log.handlers) > 0 else logging.StreamHandler(sys.stdout)
    # stream_handler.setLevel(logging.INFO)

    # 设置控制台文件输出
    file_info_handler = TimedRotatingFileHandler(info_dir, when="D", interval=1)
    file_err_handler = TimedRotatingFileHandler(error_dir, when="D", interval=1)

    # 设置日志输出格式：
    stream_handler.setFormatter(fmt)
    file_info_handler.setFormatter(fmt)
    file_err_handler.setFormatter(fmt)

    # 设置过滤条件
    info_filter = logging.Filter()
    info_filter.filter = lambda record: record.levelno < logging.WARNING  # 设置过滤等级
    err_filter = logging.Filter()
    err_filter.filter = lambda record: record.levelno >= logging.WARNING  # 设置过滤等级

    # 对文件输出日志添加过滤条件
    file_info_handler.addFilter(info_filter)
    file_err_handler.addFilter(err_filter)

    # 对logger增加handler日志处理器
    log.addHandler(file_info_handler)
    log.addHandler(file_err_handler)
    log.addHandler(stream_handler)

    log.setLevel(log_level)
    return log


def _logger_define(log_path, log_name, log_level=logging.INFO):
    # 判断响应的文件是否存在
    if not os.path.exists(log_path):
        os.makedirs(log_path)
    log_file = os.path.join(log_path, "{}.log".format(log_name))

    # 返回一个logger对象，如果没有指定名字将返回root logger
    log = logging.getLogger()

    # 定义日志输出格式
    format = config.get("logger", "format")
    format = format if format else '[%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(funcName)s] - %(' \
                                   'message)s '
    fmt = logging.Formatter(format)

    # 设置日志控制台输出
    # stream_handler = logging.StreamHandler(sys.stdout)
    stream_handler = log.handlers[0]
    # stream_handler.setLevel(logging.INFO)

    # 设置日志文件输出
    file_handler = TimedRotatingFileHandler(log_file, when="D", interval=1)

    # 设置日志输出格式：
    stream_handler.setFormatter(fmt)
    file_handler.setFormatter(fmt)

    # 对logger增加handler日志处理器
    log.addHandler(file_handler)
    log.addHandler(stream_handler)

    log.setLevel(log_level)
    return log

def get_logger_multi_file(log_name=None, log_path=None, log_level=logging.INFO):
    log_name = log_name if log_name else __default_log_name
    log_path = log_path if log_path else __default_log_path
    log_level = log_level if log_level else __default_log_level
    return _logger_define_multi_file(log_path, log_name, log_level=log_level)


def get_logger(log_name=None, log_path=None, log_level=logging.INFO):
    log_name = log_name if log_name else __default_log_name
    log_path = log_path if log_path else __default_log_path
    log_level = log_level if log_level else __default_log_level
    return _logger_define(log_path, log_name, log_level=log_level)
